package com.xiaoxie.web.system;

import cn.dev33.satoken.stp.StpUtil;
import com.xiaoxie.common.union.R;
import com.xiaoxie.system.domain.Permission;
import com.xiaoxie.system.domain.User;
import com.xiaoxie.system.domain.dto.LoginUser;
import com.xiaoxie.system.service.LoginService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author xiaoxie
 * @create 2025-01-20 16:04
 * @Description: 登录控制层
 */
@RestController
@RequestMapping("system/user")
@Tag(name = "登录管理",description = "登录管理")
public class LoginController {
    @Resource
    private LoginService loginService;

    /**
     * 用户登录
     * @param loginUser
     * @return
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public R login(@RequestBody LoginUser loginUser) {
        boolean loginResult = loginService.login(loginUser);
        // 如果登录成功则把token信息返回给到前端（tokenName和tokenValue是主要内容）
        return loginResult ? R.ok(StpUtil.getTokenInfo()) : R.fail("登录失败");
    }

    @GetMapping("/getPermissions")
    @Operation(summary = "获取权限")
    public R getPermission() {
        Integer uid = StpUtil.getLoginIdAsInt();
        List<Permission> permissions = loginService.getPermission(uid);
        return R.ok(permissions);
    }

    @GetMapping("/getMenu")
    @Operation(summary = "获取菜单")
    public R getMenu() {
        Integer uid = StpUtil.getLoginIdAsInt();
        List<Permission> permissions = loginService.getMenuByUserId(uid);
        return R.ok(permissions);
    }

    /**
     * 获取登录用户信息
     * @return
     */
    @GetMapping("/loginUserInfo")
    @Operation(summary = "获取登录用户信息")
    public R getLoginUserInfo() {
        User user = StpUtil.getSession().getModel("user", User.class);
        return R.ok(user);
    }

    /**
     * 退出登录
     * @return
     */
    @GetMapping("/logout")
    @Operation(summary = "退出登录")
    public R logout() {
        StpUtil.logout();
        return R.ok("退出成功");
    }

    /**
     * 自动登录
     * @return
     */
    @GetMapping("/autoLogin")
    @Operation(summary = "自动登录")
    public R autoLogin() {
        return R.ok("自动登录成功");
    }
}
